package com.liao.furns.service.impl;

import com.liao.furns.dao.FurnDAO;
import com.liao.furns.dao.OrderDAO;
import com.liao.furns.dao.OrderItemDAO;
import com.liao.furns.dao.impl.FurnDAOImpl;
import com.liao.furns.dao.impl.OrderDAOImpl;
import com.liao.furns.dao.impl.OrderItemDAOImpl;
import com.liao.furns.pojo.*;
import com.liao.furns.service.FurnService;
import com.liao.furns.service.OrderService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @author lzp
 * @version 1.0
 * lzpnb!
 */
public class OrderServiceImpl implements OrderService {
    private OrderDAO orderDAO = new OrderDAOImpl();
    private OrderItemDAO orderItemDAO= new OrderItemDAOImpl();
    private FurnDAO furnDAO = new FurnDAOImpl();
    @Override
    public String saveOrder(Cart cart, int memberId) {
        String orderId = System.currentTimeMillis() + "" + memberId;
        Order order = new Order(orderId, new Date(), cart.getCartTotalPrice(), 0, memberId);
        orderDAO.saveOrder(order);
        HashMap<Integer, CartItem> items = cart.getItems();
        Set<Integer> keys = items.keySet();
        for (Integer id : keys) {
            CartItem item = items.get(id);
            OrderItem orderItem = new OrderItem(null, item.getName(), item.getPrice(), item.getCount(), item.getTotalPrice(), orderId);
            orderItemDAO.saveOrderItem(orderItem);
            Furn furn = furnDAO.queryFurnById(id);
            furn.setSales(furn.getSales() + item.getCount());
            furn.setStock(furn.getStock() - item.getCount());
            furnDAO.updateFurn(furn);
        }
        cart.clear();
        return orderId;
    }

    @Override
    public List<Order> queryOrderByMemberID(int id) {
        return orderDAO.queryOrderByMemberID(id);
    }

    @Override
    public List<OrderItem> queryOrderItemByOrderID(String id) {
        return orderItemDAO.queryOrderItemByOrderID(id);
    }

}
